package com.valveinspectionsys.checkwork.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.valveinspectionsys.MainActivity;
import com.valveinspectionsys.R;
import com.valveinspectionsys.checkwork.db.LoginDao;
import com.valveinspectionsys.checkwork.view.UserModifyPassView;
import com.valveinspectionsys.dbhelp.DBOpenHelper;
import com.valveinspectionsys.dbhelp.DbTableName;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.httpserver.HttpClientServer;
import com.valveinspectionsys.httpserver.RequestUrl;
import com.valveinspectionsys.routing.db.DeviceRoutingDao;
import com.valveinspectionsys.server.TimingLocationService;
import com.valveinspectionsys.util.ActivityStatusUtil;
import com.valveinspectionsys.util.DateUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;


public class CheckWorkMainActivity extends Activity implements OnClickListener,BDLocationListener{
    
    private final static int DIALOG = 1;

   public Button button1;//登录
   public Button button2;//返回菜单1
   
   public Button button3;//注销
   public Button button4;//修改密码
   public Button button5;//返回菜单2
   
   public EditText edit1;//账号
   public EditText edit2;//密码
   public EditText edit3;//注销账号
   
   public RelativeLayout layout1;
   public RelativeLayout layout2;
   public RelativeLayout layout3;
   
   
   public SharedPreferenceUtil sh;
   
   public ActivityStatusUtil sta;
   
   public LocationClient client;
   
   public String status;
   
   public ProgressDialog pd;
   
   public LoginDao dao;
   
   public RequestUrl req;
   public Double latitude;
   public Double longtude;
   
   public long time;
   public boolean isStart=false;
   public List<String> waterlistid=new ArrayList<String>();
   public List<String> type=new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
	
	super.onCreate(savedInstanceState);
	
	setContentView(R.layout.checkworkmain);
	initLocation();
	
	sh=new SharedPreferenceUtil(this);
	if(sh.getBoolean(XmlNameHelper.CHECKSERVERCONNECT)&&sh.getBoolean(XmlNameHelper.workstatus)){
	    dao=new LoginDao(this, sh.getValue(XmlNameHelper.SqliteName));
	    if(!dao.isaddDeviceitem()){
		    initDate();
		}
	}

	sta=new ActivityStatusUtil(this);
	req=new RequestUrl(this);
	initUI();
                        
}

//初始化UI控件
public void initUI(){
	 button1=(Button)findViewById(R.id.checkwork_gotowork);
	 button3=(Button)findViewById(R.id.checkwork_logoff);
	 button2=(Button)findViewById(R.id.checkwork_gooffwork);
	 button4=(Button)findViewById(R.id.checkwork_modifypass);
	 button5=(Button)findViewById(R.id.checkwork_backmenu);
	 edit1=(EditText)findViewById(R.id.checkwork_username);
	 edit2=(EditText)findViewById(R.id.checkwork_pass);
	 edit3=(EditText)findViewById(R.id.checkworkmain_cancel_name);
	 edit3.setText(sh.getValue(XmlNameHelper.userName));
	 edit1.setText(sh.getValue(XmlNameHelper.userName));	 
	 layout1=(RelativeLayout)findViewById(R.id.checkwork_layout1);
	 layout2=(RelativeLayout)findViewById(R.id.checkwork_layout2);
	 layout3=(RelativeLayout)findViewById(R.id.checkwork_layout3);
	
	 button1.setOnClickListener(this);
	 button2.setOnClickListener(this);
	 button3.setOnClickListener(this);
	 button4.setOnClickListener(this);
	 button5.setOnClickListener(this);	 
	 boolean b=sh.getBoolean(XmlNameHelper.workstatus);
	 System.out.println("-------上班状态--------"+b);
	 if(b){	     
	     button1.setVisibility(View.GONE);
	     button2.setVisibility(View.GONE);
	     button3.setVisibility(View.VISIBLE);
	     button4.setVisibility(View.VISIBLE);
	     button5.setVisibility(View.VISIBLE);
	    
		   layout1.setVisibility(View.GONE);
		     layout2.setVisibility(View.GONE);
		      layout3.setVisibility(View.VISIBLE);
	 }else{
	     button1.setVisibility(View.VISIBLE);
	     button2.setVisibility(View.VISIBLE);
	     button3.setVisibility(View.GONE);
	     button4.setVisibility(View.GONE);
	     button5.setVisibility(View.GONE);
	  
	      layout1.setVisibility(View.VISIBLE);
		 layout2.setVisibility(View.VISIBLE);
		 layout3.setVisibility(View.GONE);
	 }
	 
}

@Override
public void onReceiveLocation(BDLocation location) {
	if(location!=null){
	    this.latitude=location.getLatitude();
	    this.longtude=location.getLongitude();
	}
	
	
}

@Override
public void onReceivePoi(BDLocation arg0) {
	
	
}

@Override
public void onClick(View v) {
	switch (v.getId()) {
	case R.id.checkwork_gotowork:
	    if(TextUtils.isEmpty(edit1.getEditableText().toString())||TextUtils.isEmpty(edit2.getEditableText().toString())){
		Toast.makeText(CheckWorkMainActivity.this, "账号或密码不能为空！", Toast.LENGTH_SHORT).show();
		return;
	    }
	         if( sta.isNetWork()){
	             status="登录";	          
	             pd=new ProgressDialog(this);
	             pd.setMessage("正在连接服务器....");
	             pd.show();	        
	             client.start();	      
	         }
	       intiRequest();
	    break;
	case R.id.checkwork_logoff:
	   
	    if(TextUtils.isEmpty(edit3.getEditableText().toString())){
		Toast.makeText(CheckWorkMainActivity.this, "账号不能为空！", Toast.LENGTH_SHORT).show();
	       return;
	    }
	    if( sta.isNetWork()){
	             status="注销";
	             pd=new ProgressDialog(this);
	             pd.setMessage("正在连接服务器....");
	             pd.show();
	             if(client!=null&&!client.isStarted()){
	        	 client.start();
	             }
	         }
	    intiRequest();
	    break;
	case R.id.checkwork_backmenu:
	    Intent intent=new Intent(CheckWorkMainActivity.this, MainActivity.class);
	    setResult(RESULT_OK, intent);
	    finish();
	    
	    break;
	case R.id.checkwork_gooffwork:
	    Intent intent1=new Intent(CheckWorkMainActivity.this, MainActivity.class);
	    setResult(RESULT_OK, intent1);
	    finish();
	    break;
	case R.id.checkwork_modifypass:
	    showModifyPassDialog();
	    break;
	default:
	    break;
	}
	
}
public void initLocation(){
	client=new LocationClient(this);
	LocationClientOption option = new LocationClientOption();
	// 打开GPS
	option.setOpenGps(true);
	// 设置坐标类型
	option.setCoorType("bd09ll");

	// 设置网络优先
	
       option.setPriority(LocationClientOption.GpsFirst);
	// 设置产品线名称
	option.setProdName("waterSys");
	option.setScanSpan(5000);
	// 是否启用缓存定位
	option.disableCache(true);
	client.setLocOption(option);
	client.registerLocationListener(this);
	
  }
	
//上下班发起的请求
public String Work( ){

	System.out.println("------发起请求---1111111-----");
	Map<String, String> map=new HashMap<String, String>();
	if(status.equals("登录")){
	    map.put("name", edit1.getEditableText().toString());
	    map.put("pass", edit2.getEditableText().toString());
	}else{
	    map.put("name", edit3.getEditableText().toString());
	    map.put("pass",sh.getValue(XmlNameHelper.userPASS) );
	}
	
	
    
	map.put("latitude",latitude+"");
	map.put("longitude", longtude+"");
	map.put("status", status);
	map.put("imsi", sh.getValue(XmlNameHelper.IMEI));
	//map.put("copyerId", sh.getValue(XmlNameHelper.userID));
	map.put("date", DateUtil.getBeforeDay(0));
	HttpClientServer server=new HttpClientServer(CheckWorkMainActivity.this);
	//String respones=server.doPost(map, RequestUrl.USERLOGIN,true);
	String respones=server.doPost(map, RequestUrl.USERLOGIN,true);
	JSONObject json = null;
	String mess="";	
	System.out.println("-------------respones------------"+respones);
	if(respones.equals("error")){
	        
	        Message msg=myHandler.obtainMessage();
		msg.what=0;
		myHandler.sendMessage(msg);
		
	}else{
	    try {
		json=new JSONObject(respones);
		mess=json.getString("message");
	
		
	    } catch (JSONException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	    }
	    if(!mess.equals("yes")){
            Message msg=myHandler.obtainMessage();
		msg.what=8;
		msg.obj=mess;
		myHandler.sendMessage(msg);
       }else{

	try {
	    
	    String message=json.getString("message");
	    if(message.equals("null")){
		Message msg=myHandler.obtainMessage();
		msg.what=1;
		myHandler.sendMessage(msg);
	    }else {
		if(status.equals("登录")){
		    sh.insertValue(XmlNameHelper.workstatus, true);
		    sh.insertValue(XmlNameHelper.userName, edit1.getEditableText().toString());
		    sh.insertValue(XmlNameHelper.userPASS, edit2.getEditableText().toString());
		    sh.insertValue(XmlNameHelper.userID, json.getString("cpId"));
		    String sqliteName="water_"+sh.getValue(XmlNameHelper.userID)+".db";
		    sh.insertValue(XmlNameHelper.SqliteName, sqliteName);
		    DBOpenHelper helper = new DBOpenHelper(CheckWorkMainActivity.this,sqliteName);
		    SQLiteDatabase db = helper.getReadableDatabase();
		    db.close();
		    dao=new LoginDao(CheckWorkMainActivity.this, sqliteName);	
//			List<ContentValues>  ordertype=new ArrayList<ContentValues>();
//		    JSONArray j=json.getJSONArray("workListTypes");
//		    for(int i=0;i<j.length();i++){
//			JSONObject  jb=j.getJSONObject(i);
//			ContentValues values=new ContentValues();
//			values.put("number", jb.getString("workordertype_id"));
//			values.put("name", jb.getString("workordertype_name"));
//			values.put("status", "2");
//			ordertype.add(values);
//		    }
//		    dao.getDb().delete(DbTableName.TYPE, "status='2'", null);
//		    dao.insertALL(ordertype, DbTableName.TYPE);
		
			if(!dao.isaddDeviceitem()){
			    initDate();
			}
			
		 //   downloadData(json);			  
		    Intent intents=new Intent(CheckWorkMainActivity.this,TimingLocationService.class);
		    startService(intents);			
		    Message msg=myHandler.obtainMessage();
		    msg.what=2;
		    myHandler.sendMessage(msg);
		  
		}else if(status.equals("注销")){
		    sh.insertValue(XmlNameHelper.workstatus, false);			  
		    sh.insertValue(XmlNameHelper.userID,"");			   
		    sh.insertValue(XmlNameHelper.SqliteName, "");
		    sh.insertValue(XmlNameHelper.ReBindingTag, false);
		    sh.insertValue(XmlNameHelper.ReTuwen, false);
		    sh.insertValue(XmlNameHelper.BindingTag, false);
		    sh.insertValue(XmlNameHelper.addTuwen, false);
		    sh.insertValue(XmlNameHelper.GeneralReading, false);
		    Intent intents=new Intent(CheckWorkMainActivity.this,TimingLocationService.class);
		    stopService(intents);			
		    Message msg=myHandler.obtainMessage();
		    msg.what=5;
		    myHandler.sendMessage(msg);
		}
	    }
	} catch (JSONException e) {
	  
	    e.printStackTrace();
	}

	}
	    
	}
	

	return null;
}



@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
	if(keyCode==KeyEvent.KEYCODE_BACK){
	    if(client!=null&&client.isStarted()){
		client.stop();
		isStart=false;
	    }
	   setResult(RESULT_OK);
	}
	
	return super.onKeyUp(keyCode, event);
}

@Override
protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {
	case DIALOG:
	    Builder builder = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder.setTitle("提示信息");
	    builder.setMessage("确定要退出抄表系统吗？");
	    // 0: 默认第一个单选按钮被选中
	    builder.setPositiveButton("确定", new DialogInterface. OnClickListener() {
	        
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	            Intent intent = new Intent();   
	            intent.setAction("com.app.exit"); // 退出动作   
	            sendBroadcast(intent);// 发送广播   
	            finish();
	    	
	        }
	    });
	    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
	        
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	            dialog.dismiss(); 
	    	
	        }
	    });
	    
	    dialog=builder.create();
	    break;

	default:
	    break;
	}
	return dialog;
}

/**
 * 弹出密码修改界面
 */
public void showModifyPassDialog(){
//	LayoutInflater factory = LayoutInflater.from(this);
//	 final View textEntryView = factory.inflate(R.layout.custom_modify_copyerinfo, null);
	 final Dialog dialog = new Dialog(this, R.style.dialog);
	 dialog.setContentView(R.layout.custom_modify_copyerinfo);
	 dialog.show();
	final UserModifyPassView userview=new UserModifyPassView(this,dialog);
	 userview.button1.setOnClickListener(new OnClickListener() {
	    
	    @Override
	    public void onClick(View v) {
		if(TextUtils.isEmpty(userview.edit2.getEditableText().toString())){
		    Toast.makeText(CheckWorkMainActivity.this, "新密码不能为空!", Toast.LENGTH_SHORT).show();
		    return;
		}
		if(TextUtils.isEmpty(userview.edit3.getEditableText().toString())
			||! (userview.edit2.getEditableText().toString().equals(userview.edit3.getEditableText().toString()))){
		     Toast.makeText(CheckWorkMainActivity.this, "两次输入新密码不匹配!", Toast.LENGTH_SHORT).show();
		    return;
		}
		if(!userview.edit1.getEditableText().toString().equals(sh.getValue(XmlNameHelper.userPASS))){
		    Toast.makeText(CheckWorkMainActivity.this, "旧密码验证失败!!", Toast.LENGTH_SHORT).show();
		    return;
		}
		modifyPass(userview.edit2.getEditableText().toString(), userview.edit1.getEditableText().toString());
		
	    }
	});
	 
	 userview.button2.setOnClickListener(new OnClickListener() {
	    
	    @Override
	    public void onClick(View v) {
		dialog.dismiss();
		
	    }
	});
	 
}


//下载数据
public boolean downloadData(JSONObject json){
	List<String> l=new ArrayList<String>();
	  waterlistid.clear();
	  type.clear();
	   try {	
	 
	    JSONArray waterlistjson=json.getJSONArray("bvs");
	    List<ContentValues> waterlist=new ArrayList<ContentValues>();
	    JSONArray ordertypejson=json.getJSONArray("evs");
	    List<ContentValues> ordertype=new ArrayList<ContentValues>();
	    JSONArray authority=json.getJSONArray("avs");	    
	    JSONArray printinfo=json.getJSONArray("pmvs");
	    if(printinfo!=null&&printinfo.length()>0){
		for(int i=0;i<printinfo.length();i++){
		    JSONObject jb=printinfo.getJSONObject(i);
		    ContentValues value=new ContentValues();
		    value.put("name", jb.getString("name"));
		    String type=jb.getString("type");
		   value.put("type", type.equals("1")?"2":"3");
		   value.put("status", jb.getString("text"));
		   ordertype.add(value);
		}
	    }
	    if(waterlistjson!=null&&waterlistjson.length()>0){
		 for(int i=0;i<waterlistjson.length();i++){
		     JSONObject jb=waterlistjson.getJSONObject(i);
		     String waterlistType=jb.getString("type");
	            String waterlistStatus=jb.getString("status");
	          
	            if(waterlistType.equals(waterlistStatus)){
	        	
	        	 ContentValues value=new ContentValues();
			     value.put("waterlistid", jb.getString("bvId"));
			     value.put("number",jb.getString("number") );
			     value.put("name", jb.getString("name"));
			 
			     value.put("closdate", jb.getString("enddate"));
			     waterlistid.add(jb.getString("bvId"));
			     type.add(jb.getString("type"));
			     value.put("isdown", "0");
			     value.put("waterlisttotal", jb.getInt("count"));
			     value.put("isduplicate", jb.getString("type"));
			     value.put("isover", "0");
			     value.put("tuwenisdown", "0");
			     
			     waterlist.add(value);
			     dao.delectRewater(jb.getString("bvId"));
	            }else{
	        	l.add(jb.getString("bvId"));
	            }
		    
		 }
	    }
	   if(ordertypejson!=null&&ordertypejson.length()>0){
	       for(int i=0;i<ordertypejson.length();i++){
		   JSONObject jb=ordertypejson.getJSONObject(i);
		     ContentValues value=new ContentValues();
		    value.put("number",jb.getString("eoId") );
		     value.put("name", jb.getString("name"));
		     value.put("type", "1");
		     value.put("status", jb.getString("status"));
		     ordertype.add(value);
	       }
	   }
	   
	   if(authority!=null&&authority.length()>0){
	    
	       sh.insertValue(XmlNameHelper.GeneralReading,false);
	       sh.insertValue(XmlNameHelper.BindingTag, false);
	       sh.insertValue(XmlNameHelper.addTuwen, false);
	       sh.insertValue(XmlNameHelper.ReBindingTag, false);
	       sh.insertValue(XmlNameHelper.ReTuwen, false);
	       for(int i=0;i<authority.length();i++){
		   JSONObject jb=authority.getJSONObject(i);
		   String str=jb.getString("number");
		   System.out.println("---------str--------"+str);
		   if(jb.getString("number").equals("002")){
		       sh.insertValue(XmlNameHelper.GeneralReading,true);
		   }else if(str.equals("003")){
		       sh.insertValue(XmlNameHelper.BindingTag, true);
		   }else if(str.equals("004")){
		       sh.insertValue(XmlNameHelper.addTuwen, true);
		   }else if(str.equals("005")){
		       sh.insertValue(XmlNameHelper.ReBindingTag, true);
		   }else if(str.equals("006")){
		       sh.insertValue(XmlNameHelper.ReTuwen, true);
		   }
	       }
	   }
	   dao.delectAll(DbTableName.TYPE);
	   List<String> listw=dao.queryAllWaterlistId();
	   if(listw!=null&&listw.size()>0){
	       if(l!=null&&l.size()>0){
		   listw.removeAll(l);
	       }	    
	       System.out.println("---------------"+listw.size());
	          for(int i=0;i<listw.size();i++){
	              System.out.println("----------被删除的表册ID----------"+listw.get(i));
	              dao.delectRewater(listw.get(i));
	          }
	   }
	  
	   dao.insertALL(waterlist, DbTableName.DEVICEINFO);
	   dao.insertALL(ordertype, DbTableName.TYPE);
	} catch (JSONException e) {	  
	    e.printStackTrace();
	}
	return false;
	
}

Handler myHandler=new Handler(){

	@Override
	public void handleMessage(Message msg) {
	     if(msg.what==1){		
	         client.stop();
	         pd.dismiss();
		 Toast.makeText(CheckWorkMainActivity.this, "输入信息有误", Toast.LENGTH_SHORT).show();
	     }else if(msg.what==2){
		 pd.dismiss();
	         client.stop();
		 Toast.makeText(CheckWorkMainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
		 sh.insertValue(XmlNameHelper.UnlockStatus, true);
		// Response();
	     }else if(msg.what==3){
		 pd.dismiss();
		 Toast.makeText(CheckWorkMainActivity.this, "修改密码失败", Toast.LENGTH_SHORT).show();
	     }else if(msg.what==4){
		 pd.dismiss();
		 Toast.makeText(CheckWorkMainActivity.this, "修改密码成功", Toast.LENGTH_SHORT).show();
		 sh.insertValue(XmlNameHelper.workstatus, false);
		 sh.insertValue(XmlNameHelper.userID, "");
		 setResult(RESULT_OK);
		 finish();
		 
	     }else if(msg.what==5){
		 sh.insertValue(XmlNameHelper.UnlockStatus, false);
		 pd.dismiss();
		 client.stop();
//		 Intent intent=new Intent("com.app.exit");
//		       sendBroadcast(intent);
		 setResult(RESULT_OK);
		       finish();
	     }else if(msg.what==7){
		
		 setResult(RESULT_OK);
		 finish();
	     }else if(msg.what==0){
		    isStart=false;
		  client.stop();
		   pd.dismiss();
	           Toast.makeText(CheckWorkMainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show();
	     }else if(msg.what==8){
		   isStart=false;
		   client.stop();
		   pd.dismiss();
		   sh.insertValue(XmlNameHelper.GPSLATITUDE, "0.0");
		   sh.insertValue(XmlNameHelper.GPSLONGITUDE, "0.0");
		   sh.insertValue(XmlNameHelper.GPSDATE, "0");
	           Toast.makeText(CheckWorkMainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
	     }
	    super.handleMessage(msg);
	}
	
};

//发起请求
public void intiRequest(){
	  time=System.currentTimeMillis();
	         latitude=0.0;
	         longtude=0.0;
	         isStart=true;
	         new Thread(){

		    @Override
		    public void run() {
			while(isStart){
			           if(latitude>0){
			               isStart=false;
			             Work();
			           }
			           try {
				    Thread.sleep(500);
				    if((System.currentTimeMillis()-time)>5000&&isStart){
					isStart=false;
					 Work();
				    }
				} catch (InterruptedException e) {
				   
				    e.printStackTrace();
				}
				super.run();
			    
			}
		    }
	             
	         }.start();
}

//修改密码
public void modifyPass(final String pass,final String oldpass){
	pd=new ProgressDialog(this);
	pd.setMessage("正在提交信息..");
	pd.show();
	new Thread(){

	    @Override
	    public void run() {
	           Map<String, String> map=new HashMap<String, String>();
	           map.put("imei", sh.getValue(XmlNameHelper.IMEI));
	           map.put("copyerId", sh.getValue(XmlNameHelper.userID));
	           map.put("pass", pass);
	           map.put("oldPass", oldpass);
	           HttpClientServer  server=new HttpClientServer(CheckWorkMainActivity.this);
	           String response=server.doPost(map, RequestUrl.MODIFYPASS,true);
	           System.out.println("----------修改密码------"+response);
	           if(response.equals("error")){
	               Message msg=myHandler.obtainMessage();
	               msg.what=3;
	               myHandler.sendMessage(msg);
	           }else{
	               JSONObject json;
		    try {
			json = new JSONObject(response);
			 String message=json.getString("message");
			      if(message.equals("no")){
		        	   Message msg=myHandler.obtainMessage();
			               msg.what=3;
			               myHandler.sendMessage(msg);
		               }else{
		        	   sh.insertValue(XmlNameHelper.userPASS,pass);
		        	   Message msg=myHandler.obtainMessage();
			               msg.what=4;
			               myHandler.sendMessage(msg);
		               }
		    } catch (JSONException e) {
			       Message msg=myHandler.obtainMessage();
		               msg.what=3;
		               myHandler.sendMessage(msg);
			e.printStackTrace();
		    }
	              	         	             
	           }
		super.run();
	    }
	    
	}.start();
}

@Override
protected void onDestroy() {
	if(dao!=null){
		dao.close();
	}

	super.onDestroy();
}

//下载表册成功后返回给后台数据
public void Response(){
     new Thread(){

	    @Override
	    public void run() {
		Map<String, String> map=new HashMap<String, String>();
		map.put("copyerId", sh.getValue(XmlNameHelper.userID));
		map.put("imei", sh.getValue(XmlNameHelper.IMEI));
		
		String bookids="";
		
		if(waterlistid!=null&&waterlistid.size()>0){
		    for(int i=0;i<waterlistid.size();i++){
			    bookids=waterlistid.get(i)+","+type.get(i)+";"+bookids;
			}
		}
		map.put("bookIds", bookids);
		HttpClientServer server=new HttpClientServer(CheckWorkMainActivity.this);
	        String str=server.doPost(map, RequestUrl.CALLBACKWATERLIST, true);
	      
	        if(str.equals("error")){
	            Message msg=myHandler.obtainMessage();
	            msg.what=6;
	            myHandler.sendMessage(msg);
	        }else{
	            Message msg=myHandler.obtainMessage();
	            msg.what=7;
	            myHandler.sendMessage(msg);
	        }
		super.run();
	    }
         
     }.start();
}
//初始化巡检类型
public void initDate(){
	
	 String respon=getFromAssets();
	
	 if(!respon.equals("error")){
	     try {
		JSONObject  json=new JSONObject(respon);
		JSONArray  item=json.getJSONArray("item");
		JSONArray  subitem=json.getJSONArray("subitem");
		List<ContentValues> itemlist=new ArrayList<ContentValues>();
		List<ContentValues> sublist=new ArrayList<ContentValues>();
		for(int i=0;i<item.length();i++){
		    JSONObject jb=item.getJSONObject(i);
		    ContentValues value=new ContentValues();
		    value.put("number", jb.getString("deviceItemNumber"));
		    value.put("name", jb.getString("deviceItemName"));
		    value.put("forcedpictures", jb.getString("deviceItemType"));
		    value.put("type", jb.getString("deviceItemType"));
		    itemlist.add(value);
		}
		for(int i=0;i<subitem.length();i++){
		    JSONObject jb=subitem.getJSONObject(i);
		    ContentValues value=new ContentValues();
		    value.put("number", jb.getString("number"));
		    value.put("name", jb.getString("name"));
		    value.put("itemNumber", jb.getString("deviceItemNumbeer"));
		  
		    sublist.add(value);
		}
		LoginDao dao=new LoginDao(this, sh.getValue(XmlNameHelper.SqliteName));
		dao.insertALL(sublist, DbTableName.DEVICESUBITEM);
		boolean b=dao.insertALL(itemlist, DbTableName.DEVICEITEM);
		
	    } catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	     
	 }
	
}
//读取assets下文件流
public String getFromAssets(){
	InputStreamReader inputReader=null;
	 BufferedReader bufReader =null;
	  String line="";
      String Result="";
	try {
	     inputReader = new InputStreamReader( getResources().getAssets().open("devicejson.text") );
	     bufReader = new BufferedReader(inputReader);
      
        while((line = bufReader.readLine()) != null){
    	   Result += line;
        }
	} catch (IOException e) {
	    System.out.println("---  e.printStackTrace();------");
	    e.printStackTrace();
	}finally{
	    if(bufReader!=null){
		try {
		    bufReader.close();
		} catch (IOException e) {
		 
		    e.printStackTrace();
		}
	    }
	    if(inputReader!=null){
		try {
		    inputReader.close();
		} catch (IOException e) {
		 
		    e.printStackTrace();
		}
	    }
	} 

	return Result;
	
}
}
